package com.fly.source.ui;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Frame;
import java.awt.HeadlessException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import com.fly.source.utils.Executor;
import com.fly.source.utils.MvnUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 工具UI简化版本
 * 
 * @author 00fly
 * @version [版本号, 2023年3月3日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
public class SimpleSourceUI extends JFrame
{
    private static final long serialVersionUID = -6346496604061152215L;
    
    JFrame frame = this;
    
    public SimpleSourceUI()
        throws HeadlessException
    {
        initComponent();
        this.setVisible(true);
        this.setResizable(true);
        this.setAlwaysOnTop(true);
        this.setTitle("POM源码工具 V1.0");
        this.setBounds(400, 200, 1200, 550);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        try
        {
            // 设定用户界面的外观
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);
        }
        catch (Exception e)
        {
        }
    }
    
    /**
     * 组件初始化
     * 
     * @see [类、类#方法、类#成员]
     */
    private void initComponent()
    {
        // 加载图标
        URL imgURL = getClass().getResource("/img/icon.gif");
        if (imgURL != null)
        {
            setIconImage(getToolkit().createImage(imgURL));
        }
        
        JTextArea textArea = new JTextArea();
        textArea.setToolTipText("请输入dependencies节点内容, 例如：<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.15.0</version></dependency>");
        textArea.setText("<!-- 请替换下面内容 -->\n<dependency>\n  <groupId>commons-io</groupId>\n  <artifactId>commons-io</artifactId>\n  <version>2.15.0</version>\n</dependency>");
        
        // JTextArea不自带滚动条，因此就需要把文本区放到一个滚动窗格中
        JScrollPane scroll = new JScrollPane(textArea);
        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        
        JButton button = new JButton(" 获 取 源 码 包 ");
        this.add(scroll, BorderLayout.CENTER);
        this.add(button, BorderLayout.SOUTH);
        button.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent event)
            {
                try
                {
                    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                    String dependencies = textArea.getText();
                    if (StringUtils.isBlank(dependencies))
                    {
                        throw new Exception("dependencies节点内容不合法，请修改");
                    }
                    try (InputStream is = QuickSourceUI.class.getResourceAsStream("/pom.tpl"))
                    {
                        String pomTemplate = IOUtils.toString(is, StandardCharsets.UTF_8);
                        String pom = String.format(pomTemplate, dependencies);
                        File dest = new File("upload/pom.xml");
                        FileUtils.writeStringToFile(dest, pom, StandardCharsets.UTF_8, false);
                        
                        // 运行package命令，通过pom文件中的插件maven-dependency-plugin收集jar到lib
                        String pomPath = dest.getCanonicalPath();
                        log.info("pom.xml 文件路径：{}", pomPath);
                        Executor.execute("mvn clean package -f " + pomPath).forEach(log::info);
                        // 收集sources
                        MvnUtils.copyResource(pomPath);
                        setExtendedState(Frame.ICONIFIED);
                    }
                }
                catch (Exception e)
                {
                    JOptionPane.showMessageDialog(frame, e.getMessage(), "系統异常", JOptionPane.ERROR_MESSAGE);
                }
                finally
                {
                    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                }
            }
        });
    }
    
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(() -> new SimpleSourceUI());
    }
}
